from rest_framework import serializers
from .models import Ticket, TicketAssignment, TicketAction, TicketStatus
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name']


class TicketSerializer(serializers.ModelSerializer):
    creator = UserSerializer(read_only=True)
    current_handler = UserSerializer(read_only=True)
    current_status_display = serializers.ReadOnlyField(source='get_current_status_display')

    class Meta:
        model = Ticket
        fields = [
            'id', 'title', 'description', 'creator', 'current_status', 
            'current_status_display', 'current_handler', 'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at']


class TicketAssignmentSerializer(serializers.ModelSerializer):
    ticket = TicketSerializer(read_only=True)
    handler = UserSerializer(read_only=True)
    status_at_assignment_display = serializers.ReadOnlyField(source='get_status_at_assignment_display')

    class Meta:
        model = TicketAssignment
        fields = [
            'id', 'ticket', 'handler', 'assigned_at', 'status_at_assignment', 
            'status_at_assignment_display', 'notes'
        ]
        read_only_fields = ['assigned_at']


class TicketActionSerializer(serializers.ModelSerializer):
    ticket = TicketSerializer(read_only=True)
    actor = UserSerializer(read_only=True)
    next_handler = UserSerializer(read_only=True)
    from_status_display = serializers.ReadOnlyField(source='get_from_status_display')
    to_status_display = serializers.ReadOnlyField(source='get_to_status_display')

    class Meta:
        model = TicketAction
        fields = [
            'id', 'ticket', 'actor', 'action_time', 'from_status', 
            'from_status_display', 'to_status', 'to_status_display', 
            'comment', 'next_handler'
        ]
        read_only_fields = ['action_time']


class TicketStatusSerializer(serializers.Serializer):
    value = serializers.CharField()
    display_name = serializers.CharField()

    def to_representation(self, instance):
        return {
            'value': instance[0],
            'display_name': instance[1]
        }